'use strict';
const Service = require('egg').Service;
const qs = require('querystring');
// const marked = require('marked');
const dayjs = require('dayjs');

class CmsService extends Service {

  async getCategorieList() {
    const app = this.app;
    const url = `${app.config.cms.host}/getCategorieList.json`;

    const result = await this.ctx.curlGet(url);

    if (result && result.list) {
      return [ result.list ];  
    }

    return [ ];
  }

  async getTopicDetail({ id }) {
    const detailQuery = { _id: id };
    const contentDetail = await this.ctx.model.Content.findOne(detailQuery).exec();

    const result = {
      detail: contentDetail,
    }

    if (result && result.detail) {
      result.detail.date = dayjs(result.detail.date).format('YYYY-MM-DD HH:mm:ss');
    }
    return [ result.detail ];
  }

  async getTopicList({ pageNum, pageSize }) {
    const app = this.app;

    const params = {
      pageNum,
      pageSize,
    };

    const url = `${app.config.cms.host}/publiccms/api/wx/cms/content/list.json?${qs.stringify(params)}`;
    const result = await this.ctx.curlGet(url);
    if (result) {
      return [ result.data.items, result.data.totalCount ];
    }

    return [ ];
  }

  async getPubliccmsTopicDetail({ id }) {
    const app = this.app;

    const params = {
      id,
    };

    const url = `${app.config.cms.host}/publiccms/api/wx/cms/content/detail.json?${qs.stringify(params)}`;
    const result = await this.ctx.curlGet(url);
    if (result) {
      return [ result.data ];
    }

    return [ ];
  }
}

module.exports = CmsService;
